<template>
  <div class="forget-password">
    <!-- 头部导航 -->
    <div class="header">
      <img src="/static/images/back.svg" alt="返回" @click="back" class="back-icon">
      <text class="title">找回密码</text>
    </div>

    <!-- 表单区域 -->
    <div class="form-container">
      <div class="form-item">
        <label>手机号</label>
        <input type="tel" v-model="phone" placeholder="请输入注册手机号" maxlength="11" class="form-input">
      </div>

      <div class="form-item code-item">
        <div class="code-input">
          <label>验证码</label>
          <input type="number" v-model="code" placeholder="请输入验证码" maxlength="6" class="form-input">
        </div>
        <button class="get-code-btn" :disabled="isCountingDown" @click="getVerificationCode">
          {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
        </button>
      </div>

      <div class="form-item">
        <label>新密码</label>
        <input type="password" v-model="password" placeholder="请设置新密码（6-20位字符）" class="form-input">
      </div>

      <div class="form-item">
        <label>确认密码</label>
        <input type="password" v-model="confirmPassword" placeholder="请再次输入新密码" class="form-input">
      </div>
    </div>

    <!-- 提交按钮 -->
    <button class="submit-btn" :disabled="!canSubmit" @click="submit">
      完成
    </button>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onUnmounted } from 'vue'
import { http } from '@/pages/utils/Http'
import type { ResetPasswordResponse } from '@/pages/utils/request'

const phone = ref('')
const code = ref('')
const generatedCode = ref('')
const password = ref('')
const confirmPassword = ref('')
const countdown = ref(0)
const isCountingDown = ref(false)
let timer: number | null = null

// 返回上一页
const back = () => {
  uni.navigateBack()
}

// 获取验证码
const getVerificationCode = () => {
  if (!phone.value) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }

  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  // 生成 6 位随机验证码
  generatedCode.value = Math.floor(100000 + Math.random() * 900000).toString()
  console.log('本次验证码：', generatedCode.value)

  // 开始倒计时
  countdown.value = 60
  isCountingDown.value = true
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer as number)
      timer = null
      isCountingDown.value = false
    }
  }, 1000)

  uni.showToast({
    title: '验证码已生成（请看控制台）',
    icon: 'none'
  })
}

// 提交表单
const submit = async () => {
  if (!phone.value || !code.value || !password.value || !confirmPassword.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  // 校验验证码
  if (code.value !== generatedCode.value) {
    uni.showToast({
      title: '验证码错误',
      icon: 'none'
    })
    return
  }

  if (password.value !== confirmPassword.value) {
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    })
    return
  }

  if (password.value.length < 6 || password.value.length > 20) {
    uni.showToast({
      title: '密码长度应为6-20位',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({ title: '正在提交...' })
    const res = await http.put<ResetPasswordResponse>('/api/forgotPassword', {
      phone: phone.value,
      newPassword: password.value,
    })
    uni.hideLoading()
    if (res.code === 200) {
      uni.showToast({ title: '密码重置成功', icon: 'success' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({ title: res.message || '密码重置失败', icon: 'none' })
    }
  } catch (err: any) {
    uni.hideLoading()
    uni.showToast({ title: err?.message || '密码重置失败', icon: 'none' })
  }
}

// 是否可以提交
const canSubmit = computed(() => {
  return phone.value && code.value && password.value && confirmPassword.value
})

// 清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
</script>

<style scoped lang="scss">
.forget-password {
  width: 100%;
  max-width: 500px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
  background-color: #fff;
  position: relative;
  overflow-y: auto;
}


.header {
  width: 100%;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-top: 40px;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;

  .back-icon {
    width: 40rpx;
    height: 40rpx;
    position: absolute;
    left: 0rpx;
    cursor: pointer;
  }
}

.form-container {
  width: 100%;
  margin-top: 60rpx;
  display: flex;
  flex-direction: column;
}

.form-item {
  width: 100%;
  margin-bottom: 40rpx;

  label {
    display: block;
    margin-bottom: 10rpx;
    font-size: 28rpx;
    color: #333;
  }

  .form-input {
    width: 100%;
    height: 70rpx;
    border-bottom: 1px solid #eee;
    padding: 0;
    font-size: 28rpx;
    color: #333;

    &::placeholder {
      color: #ccc;
      font-size: 28rpx;
    }
  }
}

.code-item {
  display: flex;
  align-items: flex-end;
  /* 底部对齐 */

  .code-input {
    flex: 1;
    margin-right: 20rpx;
  }
}

.get-code-btn {
  width: 180rpx;
  height: 56rpx;
  line-height: 52rpx;
  color: #6f76fb;
  font-size: 24rpx;
  background: none;
  border: 1px solid #6f76fb;
  border-radius: 28rpx;
  padding: 0;
  white-space: nowrap;
  margin-bottom: 4rpx;
  /* 微调使与输入框对齐 */

  &[disabled] {
    color: #999;
    border-color: #ccc;
  }
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  margin-top: 60rpx;
  background-color: #6f76fb;
  color: white;
  border: none;
  border-radius: 45rpx;
  font-size: 32rpx;
  transition: background-color 0.3s;

  &:active {
    background-color: #5a62d8;
  }

  &[disabled] {
    background-color: #ccc;
  }
}
</style>